package com.cnyao.phot;

import java.util.HashMap;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

/*
 * The class UserAdapter is work for to get the data in the
 * SQLite Database and fill them into the ListView etc...
 * */
public class UserAdapter extends CursorAdapter {

	private final LayoutInflater mInflater;
	private final int mRealName;
	private final int mId;
	private final int mNsid;
	private final int mBuddyIcon;
	private final Drawable mDefaultIcon;
	
	private final HashMap<String, Drawable> mIcons=new HashMap<String, Drawable>();
	
	public UserAdapter(Context context, Cursor c) {
		super(context, c);
		mInflater=LayoutInflater.from(context);
		mDefaultIcon=context.getResources().getDrawable(R.drawable.chrome);
		mRealName=c.getColumnIndexOrThrow("realname");
		mId=c.getColumnIndexOrThrow(UserDatabase._ID);
		mNsid=c.getColumnIndexOrThrow("nsid");
		mBuddyIcon=c.getColumnIndexOrThrow("buddy_icon");
	}
	
	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		final View view=mInflater.inflate(R.layout.list_item_user, parent, false);
		final UserDescription description=new UserDescription();
		view.setTag(description);
		return view;
	}
	
	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		final UserDescription description=(UserDescription)view.getTag();
		description.id=cursor.getString(mId);
		description.nsid=cursor.getString(mNsid);
		
		final TextView textView=(TextView)view;
		textView.setText(cursor.getString(mRealName));
		
		Drawable icon=mIcons.get(description.nsid);
		if(icon==null){
			final byte[] data=cursor.getBlob(mBuddyIcon);
			Bitmap bitmap=null;
			if(data!=null){
				bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);
			}
			if(bitmap!=null){
				icon=new FastBitmapDrawable(bitmap);
			}
			else{
				icon=mDefaultIcon;
			}
			
			mIcons.put(description.nsid, icon);
		}
		textView.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
	}

	public void cleanup(){
		for(Drawable icon:mIcons.values()){
			//set the callback method to null.
			icon.setCallback(null);
		}
	}
	
	public void refresh(){
		getCursor().requery();
	}
}
